package com.ls.lserp.modules.material.web;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ls.lserp.modules.sys.utils.SystemMessageUtils;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.ls.lserp.common.config.Global;
import com.ls.lserp.common.persistence.AjaxDone;
import com.ls.lserp.common.persistence.BaseEntity;
import com.ls.lserp.common.persistence.Page;
import com.ls.lserp.common.utils.Encodes;
import com.ls.lserp.common.utils.FileUtils;
import com.ls.lserp.common.utils.ResourcesUtil;
import com.ls.lserp.common.utils.StringUtils;
import com.ls.lserp.common.utils.SystemPath;
import com.ls.lserp.common.utils.excel.ImportExcel;
import com.ls.lserp.common.web.BaseController;
import com.ls.lserp.modules.common.entity.Material;
import com.ls.lserp.modules.common.entity.UploadFile;
import com.ls.lserp.modules.job.web.DataBaseSyncJob;
import com.ls.lserp.modules.material.entity.InventoryRequest;
import com.ls.lserp.modules.material.entity.InventoryRequestEx;
import com.ls.lserp.modules.material.entity.MaterialStock;
import com.ls.lserp.modules.material.service.AMaterialService;
import com.ls.lserp.modules.order.entity.BigcargoStyle;
import com.ls.lserp.modules.order.entity.Order;
import com.ls.lserp.modules.order.entity.StyleFit;
import com.ls.lserp.modules.order.entity.StyleOptionEntity;
import com.ls.lserp.modules.setting.entity.InventoryWarning;
import com.ls.lserp.modules.setting.entity.Ognization;
import com.ls.lserp.modules.sys.entity.Brand;
import com.ls.lserp.modules.sys.entity.Sequence;
import com.ls.lserp.modules.sys.utils.DesignoptionUtils;
import com.ls.lserp.modules.sys.utils.DictUtils;
import com.ls.lserp.modules.sys.utils.SequenceUtil;
import com.ls.lserp.modules.sys.utils.UserUtils;

import groovy.util.ResourceException;

/**
 * @ClassName: materialController
 * @Description:
 * 
 * @author
 * @date 2017年1月19日 上午10:11:26
 *
 */

@Controller
@RequestMapping(value = "${adminPath}/material/stock")
public class AMaterialController extends BaseController {
	// 保存 编辑 删除 方法
	@Autowired
	private AMaterialService materialService;
	

	/**
	 * @Title: get @Description: 获取我的物料信息 @param @param
	 * id @param @return @return Material @throws
	 */

	@ModelAttribute
	public Material get(@RequestParam(required = false) String id) {

		// 判断id是否为空
		if (StringUtils.isNotBlank(id)) {

			// 执行查询语句 查询基本信息
			return materialService.get(Long.parseLong(id));
		} else {

			// 若为空，实例化
			return new Material();
		}
	}

	/**
	 * @Title: list @Description: 查询我的物料一览页面 @param @param
	 * material @param @param request @param @param response @param @param
	 * model @param @return @return String @throws
	 */

	@RequiresPermissions("material:stock:view")
	@RequestMapping(value = { "list", "" })
	public String list(Material material, HttpServletRequest request, HttpServletResponse response, Model model) {

		material.setOgnizationList(materialService.findMaterialOgnizationList(material));

		// 将实体类值赋给mvc model层返回jsp页面
		model.addAttribute("material", material);
		// 返回页面地址
		return "modules/material/Amaterial";
	}

	@RequiresPermissions("material:stock:view")
	@RequestMapping(value = { "searchList" })
	@ResponseBody
	public String searchList(Material material, HttpServletRequest request, HttpServletResponse response, Model model)
			throws ResourceException {
		material.setMaterialCode(Encodes.unescapeHtml(material.getMaterialCode()));
		material.setMaterialNameCn(Encodes.unescapeHtml(material.getMaterialNameCn()));
		material.setMaterialComposition(Encodes.unescapeHtml(material.getMaterialComposition()));
		Map<Object, Object> listMap = new HashMap<Object, Object>();
		FileUtils filUtils = new FileUtils();

		// ajax回调时使用的一览list名
		request.setAttribute(Global.LIST_NAME, "material");

		// 拼接字符串供分页使用
		StringBuilder searchParam = new StringBuilder();
		/*
		 * searchParam.append("&materialUseType=");
		 * searchParam.append(material.getMaterialUseType());
		 */
		searchParam.append("&materialTypeCd=");
		searchParam.append(material.getMaterialTypeCd());
		searchParam.append("&materialCode=");
		searchParam.append(material.getMaterialCode());
		searchParam.append("&materialComposition=");
		searchParam.append(material.getMaterialComposition());
		searchParam.append("&materialOgnizationId=");
		searchParam.append(material.getMaterialOgnizationId());
		searchParam.append("&brandCn=");
		searchParam.append(material.getBrandCn());
		searchParam.append("&materialNameCn=");
		searchParam.append(material.getMaterialNameCn());
		searchParam.append("&remarks=");
		searchParam.append(material.getRemarks());
		// 放到Attribute里，使用Global类里面的SEARCH_PAEAM作为key
		request.setAttribute(Global.SEARCH_PAEAM, searchParam.toString());

		// 当选择定制订单时，可以查询全部和定制订单信息
		if (StringUtils.isNoneBlank(material.getMaterialUseType())) {
			if (material.getMaterialUseType().equals(ResourcesUtil.getConfig("material_customization"))) {
				material.setMaterialUseType(ResourcesUtil.getConfig("material_all") + ","
						+ ResourcesUtil.getConfig("material_customization"));
			}
		}

		// 查询一览页面数据
		Page<Material> page = materialService.findList(new Page<Material>(request, response), material);

		// 读取系统路径
		String basePath = SystemPath.getClassPath();
		String tempFilePath = "//" + basePath + "templates//demoHtml//material.txt";

		// 读取文件生成字符串
		String materialHtml = readTxtFile(tempFilePath);
		String strHtml = "";
		String strImg = "";
		String strMaterialName = "";
		String strCtx = "";
		String strPopup = "";
		String detailPopup = "";
		//库存预警弹出画面
		String alertPopup = "";
		//库存预警数量
		String alertQuantity = "无";
		DecimalFormat a = new DecimalFormat("#,##0.00");
		int pageNo = 0;
		if (!"".equals(materialHtml)) {
			for (int i = 0; i < page.getList().size(); i++) {
				materialHtml = filUtils.readFileToHtml(tempFilePath);
				// 画面No
				pageNo = (page.getPageNo() - 1) * page.getPageSize() + (i + 1);
				materialHtml = materialHtml.replace("pageNo", "" + pageNo);

				// 照片
				if (StringUtils.isNotEmpty(page.getList().get(i).getFilePath())) {
					strImg = "<img src='" + page.getList().get(i).getFilePath() + "' class='tableImg'>";
				} else {
					strImg = "<img src='" + request.getContextPath() + "/static/images/pic-none.jpg' class='tableImg'>";
				}
				materialHtml = materialHtml.replace("image", "" + strImg);

				// 编码/物料名称
				if (getLanguage(request).equals("en_us")) {
					strMaterialName = StringUtils.checkStringNull(page.getList().get(i).getMaterialNameEn());
				} else {
					strMaterialName = StringUtils.checkStringNull(page.getList().get(i).getMaterialNameCn());
				}
				// 库存预警数量
				if(page.getList().get(i).getInventoryWarning() != null){
					if (page.getList().get(i).getInventoryWarning().getMaterialAlertQuantity() != null) {
						alertQuantity = page.getList().get(i).getInventoryWarning().getMaterialAlertQuantity();
					}
				}
				materialHtml = materialHtml.replace("materialName", strMaterialName);
				materialHtml = materialHtml.replace("materialCode",
						StringUtils.checkStringNull(page.getList().get(i).getMaterialCode()));
				strCtx = request.getContextPath() + Global.getAdminPath();
				strPopup = "\"popup('900px','800px','" + strCtx + "/material/stock/show?winFlag=1&id="
						+ page.getList().get(i).getId() + "')\"";
				detailPopup = "\"popup('900px','640px','" + strCtx + "/material/stock/viewMaterialStock?id="
						+ page.getList().get(i).getId() + "')\"";
				alertPopup = "\"popup('900px','220px','" + strCtx + "/material/stock/inventoryAlertEdit?materialId="
						+ page.getList().get(i).getId() 
						+ "&materialAlertQuantity=" + alertQuantity
						+ "&factoryId=" + page.getList().get(i).getMaterialOgnizationId()
						+ "&materialCode=" + page.getList().get(i).getMaterialCode()
						+ "&customerName=" + page.getList().get(i).getOgnizationName()
						+ "&materialUnitCd=" + page.getList().get(i).getMaterialUnitCd()
						+ "')\"";
				// 物料popup
				materialHtml = materialHtml.replace("materialIdPopup", strPopup);
				// 物料popup
				materialHtml = materialHtml.replace("materialDetailPopup", detailPopup);
				// 物料popup
				materialHtml = materialHtml.replace("materialAlertPopup", alertPopup);
				// 业务类别
				/*
				 * materialHtml = materialHtml.replace("materialUseType",
				 * StringUtils.checkStringNull(DictUtils.getDictName(page.
				 * getList().get(i).getMaterialUseType())));
				 */
				// 物料类别
				materialHtml = materialHtml.replace("materialTypeCd",
						StringUtils.checkStringNull(DictUtils.getDictName(page.getList().get(i).getMaterialTypeCd())));
				// 克重
				materialHtml = materialHtml.replace("materialGramWeight",
						StringUtils.checkStringNull(page.getList().get(i).getMaterialGramWeight()));
				// 纱织密度
				materialHtml = materialHtml.replace("materialThreadCount",
						StringUtils.checkStringNull(page.getList().get(i).getMaterialThreadCount()));
				String materialComposition = StringUtils.checkStringNull(page.getList().get(i).getMaterialComposition());
				if (!"".equals(materialComposition)) {
					if (materialComposition.split("-").length > 1) {
						materialComposition = DesignoptionUtils.getDesignoptionName(materialComposition.replace(materialComposition.split("-")[0]+"-", ""));
					}
				}
				// 物料成分
				materialHtml = materialHtml.replace("materialComposition", materialComposition);
				// 物料风格
				materialHtml = materialHtml.replace("materialStyle",
						StringUtils.checkStringNull(DictUtils.getDictName(page.getList().get(i).getMaterialStyle())));
				// 物料颜色
				String materialColor = "";
				String materialColorList = StringUtils.checkStringNull(page.getList().get(i).getMaterialColor());
				for(String color : materialColorList.split(",")){
					materialColor += DictUtils.getDictName(color)+",";
				}
				materialHtml = materialHtml.replace("materialColor",materialColor);
				// 物料织法
				materialHtml = materialHtml.replace("materialKnitMethod", StringUtils
						.checkStringNull(DictUtils.getDictName(page.getList().get(i).getMaterialKnitMethod())));
				// 幅宽
				materialHtml = materialHtml.replace("materialSpec",
						StringUtils.checkStringNull(page.getList().get(i).getMaterialSpec()));
				materialHtml = materialHtml.replace("specUnitCd",
						StringUtils.checkStringNull(DictUtils.getDictName(page.getList().get(i).getMaterialUnitCd())));
				// 季节年份
				materialHtml = materialHtml.replace("materialYear",
						StringUtils.checkStringNull(page.getList().get(i).getMaterialYear()));
				materialHtml = materialHtml.replace("materialSeason",
						StringUtils.checkStringNull(DictUtils.getDictName(page.getList().get(i).getMaterialSeason())));
				// 客户
				materialHtml = materialHtml.replace("ognizationName",
						StringUtils.checkStringNull(page.getList().get(i).getOgnizationName()));
				// 客户品牌
				materialHtml = materialHtml.replace("brandCn",
						StringUtils.checkStringNull(page.getList().get(i).getBrandCn()));
				// 供货商
				materialHtml = materialHtml.replace("materialSupplierName",
						StringUtils.checkStringNull(page.getList().get(i).getMaterialSupplierName()));
				// 库存数量
				materialHtml = materialHtml.replace("materialQuantity",StringUtils.checkStringNull(a.format(new BigDecimal(page.getList().get(i).getMaterialQuantity())))
						);
				if (!"无".equals(alertQuantity)) {
					alertQuantity = a.format(new BigDecimal(alertQuantity));
				}
				// 库存预警数量
				materialHtml = materialHtml.replace("alertQuantity",
						StringUtils.checkStringNull(alertQuantity));

				// 描述
				materialHtml = materialHtml.replace("remarks",
						StringUtils.checkStringNull(page.getList().get(i).getRemarks()));
				strHtml += materialHtml;
				alertQuantity = "无";
			}
		}
		listMap.put("material", strHtml);
		listMap.put("page", page.getHtml());
		// ajax返回结果
		return renderString(response, listMap);
	}

	/**
	 * 
	 * 功能：Java读取txt文件的内容 1：先获得文件句柄 2：获得文件句柄当做是输入一个字节码流，需要对这个输入流进行读取
	 * 3：读取到输入流后，需要读取生成字节流
	 * 
	 * @param filePath
	 * @return html
	 */
	public String readTxtFile(String filePath) {
		String strHtml = "";
		try {
			String encoding = "UTF-8";
			File file = new File(filePath);
			// 判断文件是否存在
			if (file.isFile()) {
				InputStreamReader read = new InputStreamReader(
						// 考虑到编码格式
						new FileInputStream(file), encoding);
				BufferedReader bufferedReader = new BufferedReader(read);
				String lingText = null;
				while ((lingText = bufferedReader.readLine()) != null) {
					strHtml += lingText;
				}
				read.close();
			} else {

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return strHtml;
	}

	/**
	 * @Title: form @Description: 新建及编辑我的物料 @param @param material @param @param
	 * redirectAttributes @param @param model @param @return @return
	 * String @throws
	 */

	@RequiresPermissions("material:stock:edit")
	@RequestMapping(value = "form")
	public String form(Material material, RedirectAttributes redirectAttributes, Model model) {

		if (StringUtils.isBlank(material.getMaterialBarCode())) {

			material.setMaterialBarCode(SequenceUtil.materialbarcode().getReturnCode());
		}
		material.setOgnizationList(materialService.findMaterialOgnizationList(material));
		
		material.setButtonList(materialService.findButtonList());
		// 将实体类值赋给mvc model层返回jsp页面
		model.addAttribute("material", material);

		// 返回页面地址
		return "modules/material/AmaterialCreate";
	}

	/**
	 * @Title: checkName @Description: 查重 @param @param
	 * materialOldCode @param @param materialCode @param @return @return
	 * String @throws
	 */

	@RequiresPermissions("material:stock:edit")
	@ResponseBody
	@RequestMapping(value = "checkName")
	public String checkName(String oldMaterialCode, String materialCode) {
		try {
			oldMaterialCode = Encodes.unescapeHtml(oldMaterialCode);
			materialCode = Encodes.unescapeHtml(materialCode);
			// 页面获取数据值与旧数据若相同，并且数据值不为null
			if (materialCode != null && materialCode.toUpperCase().equals(oldMaterialCode.toUpperCase())) {
				// 返回true
				return "true";
				// 页面获取数据值与旧数据若不相同，查询结果为null，并且数据值不为null
			} else if (materialCode != null && materialService.getByCode(materialCode) == null) {
				// 返回true
				return "true";
			}
			// 数据值重名
			return "false";

		} catch (Exception e) {
			// 记录日志
			logger.error(e.getMessage(), e);
		}
		// 数据值重名
		return "false";
	}

	/**
	 * @Title: save @Description: 保存数据 @param @param material @param @param
	 * request @param @param model @param @param response @param @return @return
	 * String @throws
	 */

	@RequiresPermissions("material:stock:edit")
	@RequestMapping(value = "save")
	@ResponseBody
	public String save(Material material, UploadFile uploadFile, HttpServletRequest request, Model model,
			HttpServletResponse response) {

		// 判断id是否为null （判断新建或修改）
		if (material.getId() != null) {

			// 编辑数据
			// 判断数据是否删除
			Material materialNew = get(material.getId().toString());

			// 判断数据是否删除
			if (materialNew == null || BaseEntity.DEL_FLAG_DELETE.equals(materialNew.getDeleteFlag())) {

				// 返回提示信息
				return renderString(response,
						AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
			}

			// 排他
			if (material.getVersion() == get(material.getId().toString()).getVersion()) {

				// 版本号加1
				material.setVersion(material.getVersion() + 1);
			} else {

				// 返回提示信息
				return renderString(response,
						AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
			}
		} else {

			// 新建版本号赋值1
			material.setVersion(1L);
		}

		// 保存图片
		if (uploadFile.getFilePath() != null) {

			// 图片来源：1.电脑端 ,2.手机端
			uploadFile.setFileSource(1L);
			// 所在模块区分（1:需求单 2:款式 3:订单 4:测试 5:工艺图片）
			uploadFile.setModuleKbn(4L);
			// ftp文件名
			uploadFile.setFtpFile(ResourcesUtil.getConfig("material_picture_url"));

			// 上传文件路径(以免两个值互相影响)
			String filePath = uploadFile.getFilePath();
			// 前台显示路径
			uploadFile.setShowImgUrl(filePath);
			// 上传文件路径
			uploadFile
					.setFilePath(uploadFile.getFilePath().substring(0, uploadFile.getFilePath().lastIndexOf('/') + 1));
			// 上传文件
			uploadFile.setUploadFile(filePath.substring(filePath.lastIndexOf('/') + 1));

			material.setUploadFile(uploadFile);
		}

		try {
			// 若启用未选择赋值1
			if (material.getEnableFlag() == null) {
				material.setEnableFlag("1");
			}
			material.setMaterialCode(Encodes.unescapeHtml(material.getMaterialCode()));
			// 保存我的物料
			materialService.saveMaterial(material);

			// 保存成功返回提示信息
			return renderString(response, AjaxDone.ok(SystemMessageUtils.getMessageName(
					"materialSaveSuccess")));
		} catch (Exception e) {
			// 记录日志
			logger.error(e.getMessage(), e);
			// 提示错误信息
			return renderString(response, AjaxDone.error(getText("System_error_please_contact_your_administrator")));
		}
	}

	/**
	 * @Title: show @Description: 查看我的物料 @param @param material @param @param
	 * model @param @return @return String @throws
	 */

	@RequiresPermissions("material:stock:view")
	@RequestMapping(value = "show")
	public String show(Material material, Model model) {

		// 将查询结果赋值mvc model层返回jsp页面
		model.addAttribute("material", material);

		// 返回页面地址
		return "modules/material/AmaterialShow";
	}

	/**
	 * @Title: delete @Description: 删除我的物料 @param @param material @param @param
	 * response @param @return @return String @throws
	 */

	@RequiresPermissions("material:stock:edit")
	@RequestMapping(value = "delete")
	public String delete(Material material, HttpServletResponse response) {

		try {

			// 执行逻辑删除方法
			materialService.deleteMaterial(material);
		} catch (Exception e) {
			// 记录日志
			logger.error(e.getMessage(), e);
			// 提示错误信息
			return renderString(response, AjaxDone.error(getText("System_error_please_contact_your_administrator")));
		}

		// 提示删除成功信息
		return renderString(response, AjaxDone.ok(getText("category_delete_success")));
	}

	/**
	  * @Title: form
	  * @Description: 库存预警编辑画面
	  * @param @param inventoryWarning
	  * @param @param redirectAttributes
	  * @param @param model
	  * @param @return
	  * @return String 
	  * @throws
	  */
	
	@RequiresPermissions("material:stock:edit")
	@RequestMapping(value = "inventoryAlertEdit")
	public String inventoryAlertEdit(InventoryWarning inventoryWarning, Model model) {
		InventoryWarning inWarning = new InventoryWarning();
	    //查询数据
		if (!"无".equals(inventoryWarning.getMaterialAlertQuantity()) && inventoryWarning.getMaterialAlertQuantity() != null) {
			inWarning = materialService.getInventoryWarningInfo(inventoryWarning);
		}
		//将实体类值赋给mvc model层返回jsp页面
		model.addAttribute("inventoryWarning", inventoryWarning);
		model.addAttribute("inWarning", inWarning);
		
		// 返回页面地址
		return "modules/setting/inventoryWarningShow";
	}
	
	/**
	  * @Title: form
	  * @Description: 库存预警编辑画面
	  * @param @param inventoryWarning
	  * @param @param redirectAttributes
	  * @param @param model
	  * @param @return
	  * @return String 
	  * @throws
	  */
	
	@RequiresPermissions("material:stock:edit")
	@RequestMapping(value = "saveInventoryAlert")
	public String saveInventoryAlert(InventoryWarning inventoryWarning, Model model,HttpServletResponse response) {
		String flag = "false";
		try {
			//编辑数据
			inventoryWarning.preInsert();
			if ("update".equals(inventoryWarning.getAlertFlag())) {
				materialService.updateInventoryWarning(inventoryWarning);
			}else {
				materialService.insertInventoryWarning(inventoryWarning);
			}
			flag = "true";
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
		}
		// 返回页面地址
		return renderString(response, flag);
	}
	
	
	/**
	 * 联动返回城市
	 * 
	 * @param user
	 * @param model
	 * @return
	 */
	@RequiresPermissions("material:stock:edit")
	@RequestMapping(value = "findOgnization")
	public String findOgnization(Material material, Model model, HttpServletResponse response) {
		// 下拉来源机构
		material.setOgnizationList(materialService.findMaterialOgnizationList(material));
		model.addAttribute("material", material);
		return "modules/material/AmaterialCreate";

	}

	/**
	 * 联动返回城市
	 * 
	 * @param user
	 * @param model
	 * @return
	 */
	@RequiresPermissions("material:stock:view")
	@RequestMapping(value = "findBrand")
	@ResponseBody
	public String findBrand(Material material, Model model, HttpServletResponse response) {
		Map<Object, Object> listMap = new HashMap<Object, Object>();		
		List<Brand> brandNameCnList = materialService.selectBrandCnList(material);
		listMap.put("brandNameCnList", brandNameCnList);
		return renderString(response, listMap);

	}

	/**
	 * excel上传画面迁移
	 * 
	 * @return
	 */
	@RequestMapping(value = { "uploadExcelFile" })
	public String popupUploadExcelFile() {
		return "modules/material/uploadMaterialExcelFile";
	}
	
	/**
	 * excel上传画面迁移
	 * 
	 * @return
	 */
	@RequestMapping(value = { "uploadExcel" })
	public String uploadExcelFile(Model model) {
		model.addAttribute("buttonName", "inOutImport");
		return "modules/material/uploadMaterialExcelFile";
	}

	/**
	 * 导入Excel
	 *
	 * @param file
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "insertExcelData", method = RequestMethod.POST)
	@ResponseBody
	public String styleSize(MultipartFile file, HttpServletResponse response) throws Exception {
		String oldFlg = "false";
		List<Material> materialList = new ArrayList<>();
		
		try {
			ImportExcel ei = new ImportExcel(file, 1, 0);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Workbook workbook = ei.wb;
			Sheet st = workbook.getSheetAt(0);
			int rowmun = st.getPhysicalNumberOfRows();
			// 日期初期化
			Date dateCell = new Date();
			String cellStr;
			Map<String,Material> importMap = new HashMap<String,Material>();
			// 原辅料实体类
			Material material1 = new Material();

			// 
			boolean orderPartsFlg = false;
			int count = 0;
			
			for (int i = 1; i < rowmun; i++) {
				// 面料号
				if (st.getRow(i) != null) {
					cellStr = getCellValue(st.getRow(i).getCell(1));
					if (!"".equals(cellStr)) {
						material1.setMaterialCode(cellStr.trim());
						// 物料类别
						cellStr = getCellValue(st.getRow(i).getCell(2));
						material1.setMaterialTypeCd(valuechange(cellStr));
						// 面料名
						cellStr = getCellValue(st.getRow(i).getCell(3));
						material1.setMaterialNameCn(cellStr);
						// 幅宽
						cellStr = getCellValue(st.getRow(i).getCell(4));
						material1.setMaterialSpec(cellStr);
						// 物料单位
						cellStr = getCellValue(st.getRow(i).getCell(5));
						material1.setMaterialUnitCd(valuechange(cellStr));
						// 物料克数
						cellStr = getCellValue(st.getRow(i).getCell(6));
						material1.setMaterialGramWeight(cellStr);
						// 物料年份
						cellStr = getCellValue(st.getRow(i).getCell(7));
						material1.setMaterialYear(cellStr);
						// 物料季节
						cellStr = getCellValue(st.getRow(i).getCell(8));
						material1.setMaterialSeason(valuechange(cellStr));
						// 物料成分
						cellStr = getCellValue(st.getRow(i).getCell(9));
						material1.setMaterialComposition(valuechange(cellStr));
						// 物料织法
						cellStr = getCellValue(st.getRow(i).getCell(10));
						material1.setMaterialKnitMethod(valuechange(cellStr));
						// 面料颜色
						cellStr = getCellValue(st.getRow(i).getCell(11));
						material1.setMaterialColor(cellStr);
						// 风格
						cellStr = getCellValue(st.getRow(i).getCell(12));
						material1.setMaterialStyle(valuechange(cellStr));
						// 物料用途
						cellStr = getCellValue(st.getRow(i).getCell(13));
						if (cellStr!=null&&cellStr!="") {
							cellStr = cellStr.split(":")[0];
						}
						material1.setMaterialUseType(valuechange(cellStr));
						// 纱支/密度
						cellStr = getCellValue(st.getRow(i).getCell(14));
						material1.setMaterialThreadCount(cellStr);
						// 客户
						cellStr = getCellValue(st.getRow(i).getCell(15));
						material1.setVenderId(valuechange(cellStr));
						// 品牌
	//					cellStr = getCellValue(st.getRow(i).getCell(16));
	//					material1.setBrandName(cellStr);
						// 供应商
						cellStr = getCellValue(st.getRow(i).getCell(17));
						material1.setMaterialSupplierName(cellStr);
						// 物料级别
						cellStr = getCellValue(st.getRow(i).getCell(18));
						material1.setMaterialLevel(valuechange(cellStr));
						// 产地
						cellStr = getCellValue(st.getRow(i).getCell(19));
						material1.setMaterialProduced(cellStr);
						// 面料使用类别
						cellStr = getCellValue(st.getRow(i).getCell(20));
						if (cellStr!=null&&cellStr!="") {
							cellStr = cellStr.split(":")[0];
						}
						material1.setMaterialType(cellStr);
						// 条形码
						material1.setMaterialBarCode(SequenceUtil.materialbarcode().getReturnCode());
						materialList.add(material1);
						material1 = new Material();
					}
				}
			}
			// 查重
			if (materialList != null) {
				for(Material entity :materialList){
					if(importMap.get(entity.getMaterialCode()) == null){
						importMap.put(entity.getMaterialCode(), entity);
						// 查存
						if (materialService.findMaterialExcel(entity.getMaterialCode())==false) {
							return renderString(response,AjaxDone.error("导入失败！物料" + entity.getMaterialCode() + "在系统中已存在！"));
						}
					}else {
						return renderString(response,AjaxDone.error("导入失败！物料" + entity.getMaterialCode() + "在文件内存在多个，请处理并重新导入！"));
					}
				}
			}
			// excel数据导入
			materialService.insertExcelData(materialList); 
			oldFlg = "true";
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			// 返回提示信息
			return renderString(response, oldFlg);
		}
		return renderString(response, oldFlg);
	}
	

	/**
	 * 导入Excel
	 *
	 * @param file
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "inoutImportData", method = RequestMethod.POST)
	@ResponseBody
	public String inoutImportData(MultipartFile file, HttpServletResponse response) throws Exception {
		String oldFlg = "false";
		List<Material> materialList = new ArrayList<>();
		
		try {
			ImportExcel ei = new ImportExcel(file, 1, 0);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Workbook workbook = ei.wb;
			Sheet st = workbook.getSheetAt(0);
			int rowmun = st.getPhysicalNumberOfRows();
			// 日期初期化
			Date dateCell = new Date();
			String cellStr;
			String flag;
			 
			// 原辅料实体类
			Material material = new Material();
			Material material2 = new Material();
			List<InventoryRequest> warehouseRackList = materialService.checkWarehouseRack();
			List<InventoryRequestEx> venderBrandList = materialService.checkVenderBrand();
			// 
			boolean orderPartsFlg = false;
			int count = 0;
			for (int i = 1; i < rowmun; i++) {
				// 面料号
				if (st.getRow(i)!=null) {
					
				
				cellStr = getCellValue(st.getRow(i).getCell(1));
				if (!"".equals(cellStr)&&cellStr!=null) {
					material.setMaterialCode(cellStr);
					// 入出库区分
					cellStr = getCellValue(st.getRow(i).getCell(2));
					material.setInventoryInOutKbn(cellStr.split(":")[0]);
					// 客户
					cellStr = getCellValue(st.getRow(i).getCell(3));
					if ("".equals(cellStr)||cellStr==null) {
						material.setCustomerIDStr("");
					}else {
						material.setCustomerIDStr(cellStr.split(":")[0]);
					}
					// 品牌
					cellStr = getCellValue(st.getRow(i).getCell(4));
					if ("".equals(cellStr)||cellStr==null) {
						material.setBrandIdStr(null);
					}else {
						material.setBrandIdStr(cellStr.split(":")[0]);
					}
					// 仓库位置（移出）
					cellStr = getCellValue(st.getRow(i).getCell(5));
					material.setOutWarehousePlace(cellStr);
					// 货架位置（移出）
					cellStr = getCellValue(st.getRow(i).getCell(6));
					material.setOutRackPlace(cellStr);
					// 入出库数量（移出）
					cellStr = getCellValue(st.getRow(i).getCell(7));
					if ("".equals(cellStr)) {
						material.setOutQuantity("0");
					}else {
						material.setOutQuantity(cellStr);
					}
					// 仓库位置（移出）
					cellStr = getCellValue(st.getRow(i).getCell(8));
					material.setInWarehousePlace(cellStr);
					// 货架位置（移入）
					cellStr = getCellValue(st.getRow(i).getCell(9));
					material.setInRackPlace(cellStr);
					// 入出库数量（移入）
					cellStr = getCellValue(st.getRow(i).getCell(10));
					if ("".equals(cellStr)) {
						material.setInQuantity("0");
					}else {
						material.setInQuantity(cellStr);
					}
					if ("1".equals(material.getInventoryInOutKbn())) {
						material2 = materialService.findMaterialExist(material);
						if (material2==null) {
							return renderString(response,AjaxDone.error(getText("material_failed_inbound")+ material.getMaterialCode().toString()+getText("material_materialcode_notexist")));
						}else {
							material.setId(material2.getId());
							flag = checkVenderBrand(venderBrandList,material.getCustomerIDStr(),material.getBrandIdStr());
							if ("false".equals(flag)) {
								return renderString(response,AjaxDone.error(getText("material_failed_inbound")+ material.getMaterialCode().toString()+getText("material_failed_venderbrand")));
							}else if("error".equals(flag)) {
								return renderString(response,AjaxDone.error(getText("material_failed_inbound")+ material.getMaterialCode().toString()+getText("material_failed_dataerror")));
							}
							flag = checkWarehouseRack(warehouseRackList,material.getInWarehousePlace(),material.getInRackPlace());
							if ("false".equals(flag)) {
								return renderString(response,AjaxDone.error(getText("material_failed_inbound")+ material.getMaterialCode().toString()+getText("material_failed_warehouserack")));
							}else if("error".equals(flag)) {
								return renderString(response,AjaxDone.error(getText("material_failed_inbound")+ material.getMaterialCode().toString()+getText("material_failed_dataerror")));
							}
						}
					}else if ("2".equals(material.getInventoryInOutKbn())) {
						material2 = materialService.findMaterialExist(material);
						if (material2==null) {
							return renderString(response,AjaxDone.error(getText("material_failed_outbound")+ material.getMaterialCode().toString()+getText("material_materialcode_notexist")));
						}else {
							material.setId(material2.getId());
							flag = checkVenderBrand(venderBrandList,material.getCustomerIDStr(),material.getBrandIdStr());
							if ("false".equals(flag)) {
								return renderString(response,AjaxDone.error(getText("material_failed_outbound")+ material.getMaterialCode().toString()+getText("material_failed_venderbrand")));
							}else if("error".equals(flag)) {
								return renderString(response,AjaxDone.error(getText("material_failed_outbound")+ material.getMaterialCode().toString()+getText("material_failed_dataerror")));
							}
							flag = checkWarehouseRack(warehouseRackList,material.getOutWarehousePlace(),material.getOutRackPlace());
							if ("false".equals(flag)) {
								return renderString(response,AjaxDone.error(getText("material_failed_outbound")+ material.getMaterialCode().toString()+getText("material_failed_warehouserack")));
							}else if("error".equals(flag)) {
								return renderString(response,AjaxDone.error(getText("material_failed_outbound")+ material.getMaterialCode().toString()+getText("material_failed_dataerror")));
							}
							Double mQuantity = materialService.findMaterialQuntity(material);
							Double mQuantity2 = materialService.findMaterialQuntityOut(material);
							if (mQuantity==null) {
								mQuantity = (double)0;
							}
							if (mQuantity2==null) {
								mQuantity2 = (double)0;
							}
							if ((mQuantity-mQuantity2)<Double.parseDouble(material.getOutQuantity())) {
								return renderString(response,AjaxDone.error(getText("material_failed_outbound")+ material.getMaterialCode().toString()+getText("material_failed_notenough")));
							}
						}
					}else if ("9".equals(material.getInventoryInOutKbn())) {
						material2 = materialService.findMaterialExist(material);
						if (material2==null) {
							return renderString(response,AjaxDone.error(getText("material_failed_movebound")+ material.getMaterialCode().toString()+getText("material_materialcode_notexist")));
						}else {
							material.setId(material2.getId());
							flag = checkVenderBrand(venderBrandList,material.getCustomerIDStr(),material.getBrandIdStr());
							if ("false".equals(flag)) {
								return renderString(response,AjaxDone.error(getText("material_failed_movebound")+ material.getMaterialCode().toString()+getText("material_failed_venderbrand")));
							}else if("error".equals(flag)) {
								return renderString(response,AjaxDone.error(getText("material_failed_movebound")+ material.getMaterialCode().toString()+getText("material_failed_dataerror")));
							}
							flag = checkWarehouseRack(warehouseRackList,material.getInWarehousePlace(),material.getInRackPlace());
							if ("false".equals(flag)) {
								return renderString(response,AjaxDone.error(getText("material_failed_movebound")+ material.getMaterialCode().toString()+getText("material_failed_warehouserack")));
							}else if("error".equals(flag)) {
								return renderString(response,AjaxDone.error(getText("material_failed_movebound")+ material.getMaterialCode().toString()+getText("material_failed_dataerror")));
							}
							flag = checkWarehouseRack(warehouseRackList,material.getOutWarehousePlace(),material.getOutRackPlace());
							if ("false".equals(flag)) {
								return renderString(response,AjaxDone.error(getText("material_failed_movebound")+ material.getMaterialCode().toString()+getText("material_failed_warehouserack")));
							}else if("error".equals(flag)) {
								return renderString(response,AjaxDone.error(getText("material_failed_movebound")+ material.getMaterialCode().toString()+getText("material_failed_dataerror")));
							}
							Double mQuantity = materialService.findMaterialQuntity(material);
							Double mQuantity2 = materialService.findMaterialQuntityOut(material);
							if (mQuantity==null) {
								mQuantity = (double)0;
							}
							if (mQuantity2==null) {
								mQuantity2 = (double)0;
							}
							if ((mQuantity-mQuantity2)<Double.parseDouble(material.getOutQuantity())) {
								return renderString(response,AjaxDone.error(getText("material_failed_movebound")+ material.getMaterialCode().toString()+getText("material_failed_notenough")));
							}
							if (Double.parseDouble(material.getInQuantity())!=Double.parseDouble(material.getOutQuantity())) {
								return renderString(response,AjaxDone.error(getText("material_failed_movebound")+ material.getMaterialCode().toString()+getText("material_failed_notequal")));
							}
						}
					}
					materialList.add(material);
					material = new Material();
					material2 = new Material();
				}
				}
			}
			// excel数据导入
			materialService.insertData(materialList); 
			oldFlg = "true";
		} catch (Exception e) {
			logger.error (e.getMessage (), e);
			// 返回提示信息
			return renderString(response, oldFlg);
		}
		return renderString(response, oldFlg);
	}
	
	/**
	 * 检查仓库货架是否正确
	 * 
	 * @param val
	 * @return
	 */
	public String checkWarehouseRack(List<InventoryRequest> list,String id1,String id2){
		String flag = "false";
		if ("".equals(id1)||"".equals(id2)||id1==null||id2==null) {
			return "error";
		}
		for (InventoryRequest inventoryRequest:list) {
			if ((id1.split(":")[0]).equals(inventoryRequest.getWarehouseID())&&(id2.split(":")[0]).equals(inventoryRequest.getRackID())) {
				flag = "true";
			}
		}
		return flag;
		
	}
	
	/**
	 * 检查客户品牌是否正确
	 * 
	 * @param val
	 * @return
	 */
	public String checkVenderBrand(List<InventoryRequestEx> list,String id1,String id2){
		String flag = "false";
		if ("".equals(id1)) {
			return "error";
		}
		for (InventoryRequestEx inventoryRequestEx:list) {
			if ((id1.split(":")[0]).equals(inventoryRequestEx.getOgnizationID())) {
				if (id2==null||"".equals(id2)) {
					flag = "true";
				}else {
					if (inventoryRequestEx.getBrandID()!=null&&!"".equals(inventoryRequestEx.getBrandID())) {
						String[] brandList = inventoryRequestEx.getBrandID().split(",");
						for (int i = 0; i < brandList.length; i++) {
							if ((id2.split(":")[0]).equals(brandList[i])) {
								flag = "true";
							}
						}
					}
				}
			}
		}
		return flag;
		
	}
	
	/**
	 * cell值转换
	 * 
	 * @param val
	 * @return
	 */
	public String valuechange(String val) {

		// 获取当前的cell值
		if (val == null || "".equals(val.trim()) || "-".equals(val.trim())) {
			return "";
		} else {
			String[] arryVal = val.split(":");
			if (arryVal.length > 1) {
				return arryVal[0];
			}
		}
		return val;
	}

	/**
	 * cell值转换(量体项目值转换)
	 * 
	 * @param val
	 * @return
	 */
	public String valuechangeInt(String val) {
		// 获取当前的cell值
		if (val == null || "".equals(val.trim()) || "-".equals(val.trim())) {
			return "-";
		} else {
			String[] arryVal = val.split("\\(");
			if (arryVal.length > 1) {
				return arryVal[0];
			}
		}
		return val;
	}

	/**
	 * 获取单元格的值
	 * 
	 * @param cell
	 * @return
	 */
	public String getCellValue(Cell cell) {
		if (cell == null)
			return "";
		if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
			return cell.getStringCellValue();
		} else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
			return String.valueOf(cell.getBooleanCellValue());
		} else if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
			return cell.getCellFormula();
		} else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
			return cell.getNumericCellValue() + "";
		}
		return "";
	}

	/**
	 * 查看一条物料出入库信息
	 * 
	 * @return
	 */
	@RequiresPermissions("material:stock:view")
	@RequestMapping(value = {"viewMaterialStock"})
	public String viewMaterialStock(Material material, HttpServletRequest request, HttpServletResponse response,
			Model model){
		material = materialService.findInOutDetail(material);
		model.addAttribute("material",material);
		return "modules/material/materialStockShow";
	}
	
	/**
	 * 物料数据同步到平台
	 * 
	 * @return
	 */
	@RequiresPermissions("material:stock:edit")
	@RequestMapping(value = {"synToMTM"})
	public String synToMTM(HttpServletRequest request, HttpServletResponse response){
		
		try {
			DataBaseSyncJob dataBaseSyncJobClass = new DataBaseSyncJob();
			dataBaseSyncJobClass.materialDataSync();
			return renderString(response, "true");
		} catch (SQLException e) {
			// 日志
			logger.error (e.getMessage (), e);
		}
		return renderString(response, "false");
		
	}
	
	/**
	 * 保存备注（出入库原因）
	 * 
	 * @return
	 */
	@RequiresPermissions("material:stock:edit")
	@RequestMapping(value = {"saveRemarks"})
	public String saveRemarks(String inventoryDetailID, String remarks, HttpServletResponse response){
		
		try {
			materialService.saveRemarks(inventoryDetailID,remarks);
			return renderString(response, "true");
		} catch (SQLException e) {
			// 日志
			logger.error (e.getMessage (), e);
		}
		return renderString(response, "false");
		
	}
	
}
